goog.provide('LocationPopup');
goog.require('goog.dom');
goog.require('goog.style');
goog.require('goog.events');

LocationPopup.show = function(latitude, longitude, callbackFn) {
    var center;
    var parsedLat = parseFloat(latitude);
    var parsedLon = parseFloat(longitude);
    var showMarker = false; 
    if (parsedLat >= -90 && parsedLat <= 90 &&
	parsedLon >= -180 && parsedLon <= 180) {
	center = new google.maps.LatLng(parsedLat, parsedLon);
	showMarker = true;
    } else {
	center = new google.maps.LatLng(24.7, 78.7);  // India
    }
    var locationPopup = goog.dom.getElementsByTagNameAndClass(
	'div', 'location-popup')[0];
    var mapElement = goog.dom.getElementsByTagNameAndClass(
	'div', 'map-element', locationPopup)[0];
    
    goog.style.showElement(locationPopup, true);

    var mapOptions = {
	zoom: 8,
	center: center,
	mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(mapElement, mapOptions);
    var marker = new google.maps.Marker({
	map: map,
	title: 'Selected Location',
	position: center
    });
    LocationPopup.markers.push(marker);

    google.maps.event.addListener(map, 'dblclick', goog.bind(
	function(mapElement, callback, map, mouseEvent) {
	    var latitude = mouseEvent.latLng.lat();
	    var longitude = mouseEvent.latLng.lng();
	    goog.style.showElement(locationPopup, false);
	    callback(latitude, longitude);
	}, null, mapElement, callbackFn, map));

    goog.events.listen(
	goog.dom.getElementsByTagNameAndClass(
	    'button', 'cancel-button', locationPopup)[0],
	goog.events.EventType.CLICK,
	function() {
	    goog.style.showElement(locationPopup, false);
	}, false, this);


    var searchBoxElement = goog.dom.getElementsByTagNameAndClass(
	'input', 'place-search-box', locationPopup)[0];
    var searchBox = new google.maps.places.SearchBox(searchBoxElement);
    searchBox.bindTo('bounds', map);
    google.maps.event.addListener(
	searchBox, 'places_changed',
	goog.bind(LocationPopup.handleSearch, null, searchBox, map));
};

LocationPopup.markers = [];

LocationPopup.handleSearch = function(searchBox, map) {
    for (var i = 0, marker; marker = LocationPopup.markers[i]; i++) {
	marker.setMap(null);
    }
    LocationPopup.markers = [];
    var places = searchBox.getPlaces();
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {
	var image = {
	    url: place.icon,
	    size: new google.maps.Size(71, 71),
	    origin: new google.maps.Point(0, 0),
	    anchor: new google.maps.Point(17, 34),
	    scaledSize: new google.maps.Size(25, 25)
	};

	var marker = new google.maps.Marker({
	    map: map,
	    icon: image,
	    title: place.name,
	    position: place.geometry.location
	});

	LocationPopup.markers.push(marker);
	bounds.extend(place.geometry.location);
    }

    map.fitBounds(bounds);
}

function callback(results, status) {
    
};
